// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import { postAnswer } from "@/services/answer";
import type { NextApiRequest, NextApiResponse } from "next";
function genAnswerInfo(reqBody: any) {
  const answerList:any = [];
  Object.keys(reqBody).forEach((key) => {
    if(key === "questionId") return;
    answerList.push({
        componentId: key,
        value: reqBody[key],
    });
  })
  return {
    questionId: reqBody.questionId || '',
    answerList,
  }
}

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse,
) {
    if(req.method !== "POST"){
        res.status(200).json({ errno: -1, message: "method 错误" });
        return;
    }
    console.log(req.body);
    const answerInfo = genAnswerInfo(req.body);
    const result = await postAnswer(answerInfo);
    try{
        if(result.errno  === 0){
            res.redirect('/success');
        }else{
            res.redirect('/fail');
        }
      
    }catch(err){
        console.log(err);
        res.redirect('/fail');

    }
    // res.status(200).json({ errno: 0, ...answerInfo});
}
